package com.voda.web.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.voda.entity.User;
import com.voda.service.api.IUserService;
import com.voda.web.util.ResponseMapUtil;


@Controller
@RequestMapping("/cms")
public class LoginController extends AbstractMappingController {

	private static final String LOGIN_URL = "/login";

	@Autowired
	private IUserService userService;
	
		
	private static final String ERROR_LOGIN_EMPTY_LOGIN = "error";
	private static final String ERROR_LOGIN_EMPTY_PASSWORD = "error";
	private static final String ERROR_LOGIN = "error";
	private static final String SUCCESS_LOGIN = "success";
	private static final String PROPERTY_LOGIN = "login";
	private static final String PROPERTY_PASSWORD = "password";
	
	@RequestMapping(value = LOGIN_URL, method = RequestMethod.POST)
	public @ResponseBody Map<Object, Object> login(@RequestBody Object data){
		JSONObject jsonObject = JSONObject.fromObject(data);
		String login =jsonObject.getString(PROPERTY_LOGIN);
		String password = jsonObject.getString(PROPERTY_PASSWORD);
		
		try {
			Assert.notNull(login, resourceBundleUtil.getMessage(ERROR_LOGIN_EMPTY_LOGIN));
			Assert.notNull(password, resourceBundleUtil.getMessage(ERROR_LOGIN_EMPTY_PASSWORD));
		} catch (IllegalArgumentException e) {
			return ResponseMapUtil.mapError(resourceBundleUtil.getMessage(ERROR_LOGIN));
		}
		
		User user = userService.findUser(login.toString(), password.toString());
		try {
			Assert.notNull(user, resourceBundleUtil.getMessage(ERROR_LOGIN));
		} catch (IllegalArgumentException e) {
			return ResponseMapUtil.mapError(resourceBundleUtil.getMessage(ERROR_LOGIN));
		}
		
		List<Object> response = new ArrayList<Object>();
		response.add(user);
		
		return ResponseMapUtil.mapSuccess(response, resourceBundleUtil.getMessage(SUCCESS_LOGIN));
	}
}
